<template>
  <el-dialog
    v-bind="$attrs"
    top="5vh"
    :close-on-click-modal="false"
    :before-close="beforeClose"
  >
    <div class="form-wrapper">
      <el-form
        style="width: 100%"
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-width="90"
      >
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group
            v-model="formData.type"
            :disabled="type === OperationType.EDIT"
            @change="typeChange"
          >
            <el-radio border :value="MenuType.FOLDER">目录</el-radio>
            <el-radio border :value="MenuType.MENU">菜单</el-radio>
            <el-radio border :value="MenuType.BUTTON">按钮</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="上级菜单" prop="parent_title">
          <el-input
            :disabled="type === OperationType.EDIT"
            ref="parentSelectRef"
            v-model="formData.parent_title"
            @focus="parentFocus"
            placeholder="请选择上级菜单"
          ></el-input>
        </el-form-item>

        <el-form-item label="菜单标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入菜单标题"></el-input>
        </el-form-item>

        <el-form-item v-if="!isButton" label="访问路径" prop="path">
          <el-input v-model="formData.path" placeholder="请输入访问路径"></el-input>
        </el-form-item>

        <el-form-item v-if="isFolder" label="重定向地址" prop="redirect">
          <el-input v-model="formData.redirect" placeholder="请输入重定向地址"></el-input>
        </el-form-item>

        <el-form-item v-if="!isButton" label="路由名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入路由名称"></el-input>
        </el-form-item>

        <el-form-item v-if="isMenu" label="文件路径" prop="component">
          <el-input v-model="formData.component" placeholder="请输入文件路径"></el-input>
        </el-form-item>

        <el-form-item v-if="!isButton" label="路由图标" prop="icon">
          <el-input v-model="formData.icon" placeholder="请输入路由图标"></el-input>
        </el-form-item>

        <el-form-item label="权限字段" prop="permission_code">
          <el-input
            v-model="formData.permission_code"
            placeholder="请输入权限字段"
          ></el-input>
        </el-form-item>

        <el-form-item label="菜单排序" prop="order_num">
          <el-input
            type="number"
            v-model.number="formData.order_num"
            placeholder="请输入菜单排序"
          ></el-input>
        </el-form-item>

        <el-form-item v-if="isMenu" label="外链地址" prop="is_link">
          <el-input
            v-model="formData.is_link"
            placeholder="如填写外链地址，会直接打开页面访问。例：https://www.baidu.com"
          ></el-input>
        </el-form-item>

        <el-form-item v-if="!isButton" label="是否隐藏" prop="is_hide">
          <el-radio-group v-model="formData.is_hide">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="!isButton" label="是否全屏" prop="is_full">
          <el-radio-group v-model="formData.is_full">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="!isButton" label="是否固定" prop="is_affix">
          <el-radio-group v-model="formData.is_affix">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="!isButton" label="是否缓存" prop="is_keep_alive">
          <el-radio-group v-model="formData.is_keep_alive">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button size="default" @click="cancel(formRef)">取消</el-button>
      <el-button type="primary" size="default" @click="submitForm(formRef)">
        确认
      </el-button>
    </template>
  </el-dialog>

  <TreeParent
    v-model="showParentDialog"
    :treeData="treeParent"
    @confirm="parentConfirm"
  ></TreeParent>
</template>

<script setup lang="ts">
import TreeParent from '@/views/system/menuMange/components/treeParent.vue'
import { MenuApi } from '@/api/interface/menu'
import { addMenuApi, updateMenuApi } from '@/api/modules/menu'
import { ElMessage, FormInstance } from 'element-plus'
import { computed, markRaw, nextTick, ref, watch } from 'vue'
import { OperationType, MenuType } from '@/enums'

const showParentDialog = ref(false)
const { type, editRow, treeParent } = defineProps(['type', 'editRow', 'treeParent'])
const emit = defineEmits(['update:modelValue', 'update', 'reset'])
const parentSelectRef = ref()
const formRef = ref<FormInstance>()
// 定义表单数据
const formData = ref<MenuApi.Menu>({
  _id: '',
  parent_id: '',
  parent_title: '',
  path: '',
  name: '',
  component: '',
  icon: '',
  title: '',
  permission_code: '',
  redirect: '',
  is_link: '',
  type: MenuType.FOLDER,
  order_num: 0,
  is_hide: 0,
  is_full: 0,
  is_affix: 0,
  is_keep_alive: 1
})
const isButton = computed(() => {
  return formData.value.type == MenuType.BUTTON
})
const isFolder = computed(() => {
  return formData.value.type == MenuType.FOLDER
})
const isMenu = computed(() => {
  return formData.value.type == MenuType.MENU
})

// 表单校验规则
const formRules = markRaw({
  path: [{ required: true, message: '路径不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  component: [{ required: true, message: '组件不能为空', trigger: 'blur' }],
  icon: [{ required: true, message: '图标不能为空', trigger: 'blur' }],
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }]
})

const typeChange = () => {
  formRef.value?.clearValidate()
}

watch(
  () => type,
  (value) => {
    if (value === OperationType.EDIT) {
      Object.assign(formData.value, editRow)
    } else {
      reset()
    }
  }
)

const reset = () => {
  formData.value = {
    _id: '',
    parent_id: '',
    parent_title: '',
    path: '',
    name: '',
    component: '',
    icon: '',
    title: '',
    permission_code: '',
    redirect: '',
    is_link: '',
    type: MenuType.FOLDER,
    order_num: 0,
    is_hide: 0,
    is_full: 0,
    is_affix: 0,
    is_keep_alive: 1
  }
  formRef.value?.clearValidate()
}
const beforeClose = () => {
  reset()
  emit('reset')
}
const cancel = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  reset()
  emit('reset')
}
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let res: any = {}
      if (type === OperationType.ADD) {
        res = await addMenuApi({ params: formData.value })
      } else if (type === OperationType.EDIT) {
        res = await updateMenuApi({ params: formData.value })
      }
      if (res.errCode === 0) {
        let message = type === OperationType.ADD ? '新增成功' : '修改成功'
        ElMessage.success(message)
        emit('update')
        beforeClose()
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
const parentFocus = () => {
  parentSelectRef.value?.blur()
  nextTick(() => {
    showParentDialog.value = true
  })
}
const parentConfirm = (data: MenuApi.Menu) => {
  formData.value.parent_id = data._id
  formData.value.parent_title = data.title
  showParentDialog.value = false
}
</script>

<style lang="scss" scoped>
.form-wrapper {
  padding: 20px;
}
</style>
